package fun.tan90.easy.binlog.plugin.redis.cluster.config;


import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.redis.cluster.listener.RedisClusterEventProcessor;
import fun.tan90.easy.binlog.plugin.redis.cluster.service.impl.RedisClusterPluginService;
import fun.tan90.easy.binlog.plugin.common.listener.CaffeineRemovalListener;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import redis.clients.jedis.JedisCluster;

import java.util.concurrent.TimeUnit;

/**
 * description
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/07/13 13:02
 */
@Slf4j
public class RedisClusterPluginAutoConfiguration {

    public RedisClusterPluginAutoConfiguration() {
        log.info("init RedisClusterPlugin");
    }

    @Bean
    public RedisClusterCacheLoader redisClusterCacheLoader() {
        return new RedisClusterCacheLoader();
    }

    @Bean
    public LoadingCache<String, JedisCluster> redisClusterCache(RedisClusterCacheLoader redisClusterCacheLoader) {
        return Caffeine.newBuilder()
                .maximumSize(10_000)
                .removalListener(new CaffeineRemovalListener(OutputTypeEnum.REDIS_CLUSTER.getOutput()))
                .expireAfterAccess(1, TimeUnit.DAYS)
                .build(redisClusterCacheLoader);
    }

    @Bean
    public RedisClusterEventProcessor redisEventProcessor(LoadingCache<String, JedisCluster> redisClusterCache) {
        return new RedisClusterEventProcessor(redisClusterCache);
    }

    @Bean(name = "redis-cluster")
    public PluginService redisClusterPluginService() {
        return new RedisClusterPluginService();
    }
}